<script setup lang="ts">
import {
  lmsSupplierConfigList,
  addlmsSupplierConfig,
  dellmsSupplierConfig,
  updatelmsSupplierConfig,
  FormlmsSupplierConfig,
} from "@/api/DataIntegration/supplier/index";
import type { RequestParams } from "@/api/DataIntegration/supplier/type";
import { ElMessage, ElMessageBox } from "element-plus";
import { onMounted, reactive, ref } from "vue";

const RobotList = ref([] as any); //列表数据

const queryFormRef = ref(); //refForm
const ids = ref([]); //表格全选
const total = ref();
const loading = ref(false);
const dialogVisible = ref(false);
const title = ref("新增");
const ruleFormRef = ref(); //弹框表单
const ruleForm = ref({
  baseConfig: [] as Array<{ key: string; value: string }>,
  formConfig: [] as Array<{ key: string; value: string }>,
} as any);
const rowId = ref();
let queryParams = ref({
  pageNum: 1,
  pageSize: 10,
} as any);
// 禁止任何空格
// const noSpace = (rule: any, value: string, cb: Function) => {
//   if (value.includes(' ')) {
//     cb(new Error('不允许输入空格'));
//   } else {
//     cb();
//   }
// };

// 禁止全空格（允许中间有空格）
const notAllSpace = (rule: any, value: string, cb: Function) => {
  if (value.trim() === "") {
    cb(new Error("不能只输入空格"));
  } else {
    cb();
  }
};

const rules = reactive({
  supplierName: [
    { required: true, message: "供应商名称不能为空", trigger: "blur" },
    { min: 1, max: 30, message: "供应商名称过长", trigger: "blur" },
    { validator: notAllSpace, trigger: "blur" }, // ← 加这里
  ],
  supplierCode: [
    { required: true, message: "供应商编码不能为空", trigger: "blur" },
    { min: 1, max: 30, message: "供应商编码过长", trigger: "blur" },
    { validator: notAllSpace, trigger: "blur" }, // ← 加这里
  ],
});
/**
 * 列表数据
 */
const getRbtList = async () => {
  try {
    const res = await lmsSupplierConfigList(queryParams.value);
    RobotList.value = res.data.records;
    total.value = res.data.total;
    console.log(res.data.records, "分页列表");
  } catch (error) {
    // console.error(error);
  }
};
/**
 * 重置
 */
const resetQuery = () => {
  queryFormRef.value.resetFields();
  queryParams.value = {} as RequestParams;
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  getRbtList();
};
/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}
/**
 * 打开弹框
 */

const openDialog = async () => {
  title.value = "新增";
  dialogVisible.value = true;
  ruleForm.value = {
    supplierName: "",
    supplierCode: "",
    baseConfig: [],
    formConfig: [],
  };
};
/**
 * 关闭弹框
 */
const close = () => {
  dialogVisible.value = false;
  ruleFormRef.value.resetFields();
  ruleFormRef.value.clearValidate();
  ruleForm.value = {} as any;
};
/**
 * 处理表单提交事件
 */
const submit = async () => {
  try {
    loading.value = true;
    const isValid = await ruleFormRef.value.validate();
    if (isValid) {
      // 转换动态表单数据为对象
      const formData = {
        ...ruleForm.value,
        baseConfig: convertToObject(ruleForm.value.baseConfig),
        formConfig: convertToObject(ruleForm.value.formConfig),
      };

      if (title.value === "新增") {
        const res = await addlmsSupplierConfig(formData);
        if (res.code === 200) {
          ElMessage.success("新增成功");
          close();
          getRbtList();
          loading.value = false;
        } else {
          ElMessage.error(res.msg);
          loading.value = false;
        }
      } else {
        const res = await updatelmsSupplierConfig(formData);
        if (res.code === 200) {
          ElMessage.success("修改成功");
          close();
          getRbtList();
          loading.value = false;
        } else {
          ElMessage.error(res.msg);
          loading.value = false;
        }
      }
    }
  } catch (error) {
    console.error(error);
    loading.value = false;
  }
};

// 编辑时处理数据
const edit = async (row: any) => {
  title.value = "编辑";
  rowId.value = row.id;

  const { data } = await FormlmsSupplierConfig(row.id);
  // 将JSON字符串转换为数组格式
  const parseConfig = (config: string) => {
    try {
      const obj = JSON.parse(config);
      return Object.entries(obj).map(([key, value]) => ({ key, value }));
    } catch {
      return [];
    }
  };

  ruleForm.value = {
    ...data,
    baseConfig: parseConfig(data.baseConfig),
    formConfig: parseConfig(data.formConfig),
  };
  dialogVisible.value = true;
};
/**
 * 删除
 */
const dell = (row: any) => {
  const userIds = [row.id || ids.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  ElMessageBox.confirm("确认删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async function () {
    const res = await dellmsSupplierConfig(row.id);
    if (res.code == 200) {
      getRbtList();
      ElMessage.success("删除成功");
    } else {
      ElMessage.error("删除失败");
    }
  });
};

onMounted(() => {
  getRbtList();
  // libOptions();
});
const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val;
  queryParams.value.pageNum = 1;

  getRbtList();
};
const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val;
  getRbtList();
  window.scrollTo({ top: 0, behavior: "smooth" }); // 立即回到顶部，并使用平滑滚动效果
};
// 控制序号
const indexMethod = (index: any) => {
  // 1、index:代表当前行数据的下标
  // 2、下标+1:  分页不要纠结：这块不是业务，完全是数学问题！
  return (
    index + 1 + (queryParams.value.pageNum - 1) * queryParams.value.pageSize
  );
};
// ----
// 新增键值对
const addKeyValue = (type: "baseConfig" | "formConfig") => {
  if (!Array.isArray(ruleForm.value[type])) {
    ruleForm.value[type] = [];
  }
  ruleForm.value[type].push({ key: "", value: "" });
};

// 删除键值对
const removeKeyValue = (type: "baseConfig" | "formConfig", index: number) => {
  ruleForm.value[type].splice(index, 1);
};

// 处理提交时的数据转换
const convertToObject = (arr: Array<{ key: string; value: string }>) => {
  return arr.reduce((acc: Record<string, string>, item) => {
    if (item.key) acc[item.key] = item.value;
    return acc;
  }, {});
};
</script>

<template>
  <div class="app-container">
    <div class="search">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="供应商编码">
          <el-input
            v-model="queryParams.supplierCode"
            placeholder="请输入供应商编码"
          />
        </el-form-item>
        <el-form-item label="供应商名称">
          <el-input
            v-model="queryParams.supplierName"
            placeholder="请输入供应商名称"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="getRbtList">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button @click="openDialog">添加</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card>
      <template #header> </template>
      <el-table
        v-loading="loading"
        highlight-current-row
        :data="RobotList"
        :border="true"
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column type="selection" width="55" :align="'center'" /> -->
        <el-table-column
          type="index"
          width="80"
          label="序号"
          :align="'center'"
          :index="indexMethod"
        />
        <el-table-column
          label="供应商编码"
          prop="supplierCode"
          :align="'center'"
        />
        <el-table-column
          label="供应商名称"
          prop="supplierName"
          :align="'center'"
        />
        <el-table-column
          label="接口基础配置"
          :align="'center'"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <pre style="margin: 0">{{ row.baseConfig }}</pre>
          </template>
        </el-table-column>

        <el-table-column
          label="表单配置"
          :align="'center'"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <pre style="margin: 0">{{ row.formConfig }}</pre>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" :align="'center'" />
        <el-table-column
          fixed="right"
          label="操作"
          :align="'center'"
          width="220"
        >
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="edit(row)"
              >编辑</el-button
            >
            <el-button type="primary" link size="small" @click="dell(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 15px"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <el-dialog
      v-model="dialogVisible"
      :title="title"
      width="600px"
      @close="close"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        status-icon
      >
        <el-form-item
          label="供应商名称"
          prop="supplierName"
          style="white-space: nowrap"
        >
          <el-input
            v-model="ruleForm.supplierName"
            placeholder="请输入供应商名称"
          />
        </el-form-item>

        <el-form-item
          label="供应商编码"
          prop="supplierCode"
          style="white-space: nowrap"
        >
          <el-input
            v-model="ruleForm.supplierCode"
            placeholder="请输入供应商编码"
          />
        </el-form-item>
        <el-form-item label="接口基础配置">
          <div
            v-for="(item, index) in ruleForm.baseConfig"
            :key="index"
            class="key-value-item"
          >
            <el-input
              v-model="item.key"
              placeholder="键"
              style="width: 200px; margin-right: 10px"
            />
            <el-input
              v-model="item.value"
              placeholder="值"
              style="width: 200px; margin-right: 10px"
            />
            <el-button
              type="danger"
              @click="removeKeyValue('baseConfig', index)"
              icon="Delete"
              circle
              plain
            />
          </div>
          <el-button type="primary" plain @click="addKeyValue('baseConfig')">
            添加配置项
          </el-button>
        </el-form-item>

        <el-form-item label="表单配置">
          <div
            v-for="(item, index) in ruleForm.formConfig"
            :key="index"
            class="key-value-item"
          >
            <el-input
              v-model="item.key"
              placeholder="键"
              style="width: 200px; margin-right: 10px"
            />
            <el-input
              v-model="item.value"
              placeholder="值"
              style="width: 200px; margin-right: 10px"
            />
            <el-button
              type="danger"
              @click="removeKeyValue('formConfig', index)"
              icon="Delete"
              circle
              plain
            />
          </div>
          <el-button type="primary" plain @click="addKeyValue('formConfig')">
            添加配置项
          </el-button>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submit">确 定</el-button>
          <el-button @click="close">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
* {
  list-style: none;
}

el-select {
  padding-bottom: 100px;
}
.key-value-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
</style>
